package com.qianyu.project.web.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qianyu.project.core.context.user.FlowUserManager;
import com.qianyu.project.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author gs
 * @date create in 2020/12/14 11:24
 */
public class JwtFilter extends OncePerRequestFilter {

    private FlowUserManager flowUserManager;

    public JwtFilter(FlowUserManager flowUserManager) {
        this.flowUserManager = flowUserManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //拿到token
        String token = httpServletRequest.getHeader("token");
        if (ObjectUtils.isEmpty(token)) {
            token = httpServletRequest.getParameter("token");
        }
        //校验
        JwtUtils.verifyToken(token);
        //拿到用户名和权限信息
        DecodedJWT decode = JWT.decode(token);
        String username = decode.getAudience().get(0);
        flowUserManager.setSysUser(username);
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(decode.getClaim("authors").asString());
        //放入SecurityContextHolder
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
